package cn.filter;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.entity.User;

public class UserFilter implements Filter {

	public void destroy() {
		System.out.println("======拦截器UserFilter关闭======");
	}
	/*
	 * 管理员访问后台的过滤器: 
	 * (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;  
        HttpServletResponse response = (HttpServletResponse) res;  
        
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("loginUser");
        if(user != null){
        	
        	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        	java.util.Date time;
			
			if(!user.getType().equals("1")){//如果用户类型不是"管理员", 则跳转到管理员登陆界面
				try {
					time = sdf.parse(sdf.format(new Date()));
					System.out.println("----"+time+" : 非管理员用户尝试访问系统模块被拒绝, 登陆用户用户名为 "+user.getUsername());
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				response.sendRedirect("../admin-login.jsp");
			}else{
				String uri = request.getRequestURI();  
		        uri = uri.substring(uri.lastIndexOf("/")+1);  
		        chain.doFilter(request, response); 
			}
		}else{
			System.out.println("----非系统用户尝试访问系统模块被拒绝-----");
			response.sendRedirect("../admin-login.jsp");
		}
        
       
		  
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("======拦截器UserFilter启动======");
	}

}
